import 'dart:convert';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'Global.dart';

class HttpGo {
  static final String GET = "get";
  static final String POST = "post";
  static final String DO_MAIN = "http://1.34.206.196/";
  // static final String DO_MAIN = "https://pcr-hb.openlife.co/";
  static Dio dio = Dio(); // 使用默认配置
  static BuildContext? _context;

  HttpGo(BuildContext context) {
    _context = context;
    dio.options.headers = {
      "Authorization": Global.token,
    };
    dio.options.baseUrl = DO_MAIN;
    dio.options.connectTimeout = 5000;
    dio.options.receiveTimeout = 3000;
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client){
      client.badCertificateCallback=(cert, host, port){
        return true;
      };
    };
  }

  LogOut(bool httpQuest) {
    // if (httpQuest) {
    //   post("api/User/logout", {}, () {}, () {});
    // }
    // Navigator.pushAndRemoveUntil(_context!, MaterialPageRoute(builder: (context) => Login()), (route) => route == null);
  }

  //get请求
  get(String url, Map<String, dynamic> params, Function successCallBack, Function errorCallBack) async {
    _requstHttp(url, successCallBack, 'get', params, errorCallBack);
  }

  //post请求
  post(String url, Map<String, dynamic> params, Function successCallBack, Function errorCallBack) async {
    _requstHttp(url, successCallBack, "post", params, errorCallBack);
  }

  download(String url, String filePath, void Function(int x, int y) progressCallBack, Function errorCallBack) async {
    dio.options.receiveTimeout = 0;
    try {
      await dio.download(url, filePath, onReceiveProgress: progressCallBack);
    } on DioError catch (e) {
      errorCallBack("400", e.message);
      if (e.response != null) {
        print("Download Error:message:" + e.message);
        print("Download Error:data" + e.response?.data);
        print("Download Error:headers" + e.response!.headers.toString());
      } else {
        print("Download Error:message" + e.message);
      }
    }
  }

  _requstHttp(String url, Function successCallBack, [String? method, params, Function? errorCallBack]) async {
    url = dio.options.baseUrl + url;
    Response? response;
    try {
      if (method == 'get') {
        if (params != null && params.length > 0) {
          response = await dio.get(url, queryParameters: params);
        } else {
          response = await dio.get(url);
        }
      } else if (method == 'post') {
        if (params != null && params.length > 0) {
          response = await dio.post(url, data: FormData.fromMap(params));
        } else {
          response = await dio.post(url);
        }
      }
    } on DioError catch (error) {
      // 请求错误处理
      Response errorResponse;
      if (error.response != null) {
        errorResponse = error.response!;
      } else {
        errorResponse = new Response(statusCode: 666, requestOptions: RequestOptions(path: ""));
      }
      // 请求超时
      if (error.type == DioErrorType.connectTimeout) {
        errorResponse.statusCode = ResultCode.CONNECT_TIMEOUT;
      }
      // 一般服务器错误
      else if (error.type == DioErrorType.receiveTimeout) {
        errorResponse.statusCode = ResultCode.RECEIVE_TIMEOUT;
      }

      print('HttpGo请求异常: ' + error.toString());
      print('HttpGo请求异常url: ' + url);
      print('HttpGo请求异常message: ' + error.message);
      print('HttpGo请求头: ' + dio.options.headers.toString());
      _error(errorCallBack, errorResponse.statusCode.toString(), error.message);
      return '';
    }
    // debug模式打印相关数据
    print('HttpGo请求url: ' + url);
    print('HttpGo请求头: ' + dio.options.headers.toString());
    print('HttpGo请求参数: ' + params.toString());
    if (response != null) {
      print('HttpGo请求：返回参数: ' + response.toString());
    }
    String dataStr = json.encode(response?.data);
    Map<String, dynamic> dataMap = json.decode(dataStr);

    if (response?.data["new_token"] != null) {
      var newToken = response?.data["new_token"].toString();
      print("NewToken----" + newToken!);
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString("token", newToken);
      Global.token = "Bearer "+ newToken;
    }
    if (response?.data["code"].toString() != "200") {
      _error(errorCallBack, (response?.data["code"]).toString(), response?.data["message"]);
      if (response?.data["code"].toString() == "202") {
        LogOut(false);
      }
    } else if (successCallBack != null) {
      successCallBack(dataMap["data"]);
    }
  }

  _error(Function? errorCallBack, String code, String error) {
    if (errorCallBack != null) {
      errorCallBack(code, error);
    }
  }
}

/*
 * dio网络请求失败的回调错误码
 */
class ResultCode {
  ///正常返回是1
  static const SUCCESS = 1;

  ///异常返回是0
  static const ERROR = 0;

  /// When opening  url timeout, it occurs.
  static const CONNECT_TIMEOUT = -1;

  ///It occurs when receiving timeout.
  static const RECEIVE_TIMEOUT = -2;

  /// When the server response, but with a incorrect status, such as 404, 503...
  static const RESPONSE = -3;

  /// When the request is cancelled, dio will throw a error with this type.
  static const CANCEL = -4;

  /// read the DioError.error if it is not null.
  static const DEFAULT = -5;
}
